import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Toast } from 'antd-mobile'
import { NavBar, Icon, Item, Image, Button } from 'components'
import { msg, post } from '../../../utils'
import moment from 'moment'
import 'moment-timezone'
import { isFunc } from 'muka'

export default class ObligationsDetail extends Component<any, any> {

    public state = {
        timeText: ''
    }

    private timer: any

    public render(): JSX.Element {
        const { orderDetail } = this.props
        const payStatus = orderDetail.pay_status || {}
        const expressInfo = orderDetail.expressInfo || { data: [] }
        return (
            <div className="obligationsDetail">
                <NavBar
                    fixed={true}
                    title={<span style={{ fontSize: '0.97rem', color: '#222' }}>订单详情</span>}
                />
                {this.getStatusNode(orderDetail.status, orderDetail)}
                {/* 用户Card信息 */}
                <div className="obligationsDetail_card">
                    <div className="obligationsDetail_card_container">
                        {orderDetail.status === 2 && (<div className="delivergoodsDetail_card_container_logistics" onClick={this.handleViewExpre}>
                            <div>
                                <Icon type="truck" />
                            </div>
                            <div>
                                <span>{expressInfo.data[0] && expressInfo.data[0].context}</span>
                                <p className="delivergoodsDetail_card_container_logistics_rightIcon"><Icon type="arrow_right" /></p>
                                <p className="delivergoodsDetail_card_container_logistics_time">{expressInfo.data[0] && expressInfo.data[0].time}</p>
                            </div>
                        </div>)}
                        {orderDetail.status === 3 && (<div className="receivedDetail_card_container_logistics" onClick={this.handleViewExpre}>
                            <div>
                                <Icon type="truck" />
                            </div>
                            <div>
                                <span>{expressInfo.data[0] && expressInfo.data[0].context}</span>
                                <p className="receivedDetail_card_container_logistics_rightIcon"><Icon type="arrow_right" /></p>
                                <p className="receivedDetail_card_container_logistics_time">{expressInfo.data[0] && expressInfo.data[0].time}</p>
                            </div>
                        </div>)}
                        {orderDetail.status === 7 && (<div className="orderCancelDetail_card_container_logistics">
                            <div>
                                <Icon type="order" />
                            </div>
                            <div>
                                <span>取消/退款进度：已取消</span>
                                <p className="orderCancelDetail_card_container_logistics_rightIcon"><Icon type="arrow_right" /></p>
                            </div>
                        </div>)}
                        {orderDetail.status !== 4 && (<div>
                            <div className="obligationsDetail_card_container_userInfo">
                                <Icon type="address" />
                                <span className="obligationsDetail_card_container_userName">{orderDetail.take_name}</span>
                                <span className="DINPro">{orderDetail.take_tel && orderDetail.take_tel.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')}</span>
                            </div>
                            <div className="obligationsDetail_card_container_address">
                                <p>{orderDetail.take_province}{orderDetail.take_city}{orderDetail.take_area}{orderDetail.take_address}</p>
                            </div>
                        </div>)}
                    </div>
                </div>
                {/* 商品信息 */}
                <div className="obligationsDetail_goodsInfo">
                    <div className="obligationsDetail_goodsInfo_container">
                        <Item
                            title={
                                <div className="obligationsDetail_goodsInfo_container_title">
                                    <Icon type="shop" />
                                    <span>{orderDetail.get_seller_name && orderDetail.get_seller_name.name}</span>
                                </div>
                            }
                        />
                        {
                            orderDetail.order_goods && orderDetail.order_goods.map((item: any, index: any) => {
                                return (
                                    <Link key={index} to={`/shopDetail/${item.goods_id}`}>
                                        <div className="obligationsDetail_goodsInfo_container_goodsWrap flex">
                                            <div>
                                                <Image src={item.pic} />
                                            </div>
                                            <div className="obligationsDetail_goodsInfo_container_goods flex_1">
                                                <div>{item.short_title}</div>
                                                <div>{item.spec}</div>
                                                <div className="flex">
                                                    <div className="flex_1">
                                                        <span>￥</span>
                                                        <span className="DINPro">{item.price} + {item.price_q}</span>
                                                        <span className="obligationsDetail_goodsInfo_container_goods_hd">恒豆</span>
                                                    </div>
                                                    {this.getStatusBtn(orderDetail.user_num, item)}
                                                </div>
                                            </div>
                                        </div>
                                    </Link>
                                )
                            })
                        }
                        <div className="obligationsDetail_goodsInfo_container_customer">
                            <Icon type="customer" />
                            <span>联系客服</span>
                        </div>
                    </div>
                </div>
                {/* 订单信息 */}
                <div className="obligationsDetail_orderInfo">
                    <div className="obligationsDetail_orderInfo_container">
                        <Item
                            title={<div className="obligationsDetail_orderInfo_container_itemtitle">订单编号：</div>}
                            value={<span className="obligationsDetail_orderInfo_container_itemtValue">{orderDetail.order_no}</span>}
                        />
                        <Item
                            title={<div className="obligationsDetail_orderInfo_container_itemtitle">下单时间：</div>}
                            value={<span className="obligationsDetail_orderInfo_container_itemtValue">{orderDetail.create_time}</span>}
                        />
                        <Item
                            title={<div className="obligationsDetail_orderInfo_container_itemtitle">支付方式</div>}
                            value={<span className="obligationsDetail_orderInfo_container_itemtValue">{this.getPayStatus(payStatus.pay_type)}</span>}
                        />
                        <Item
                            title={<div className="obligationsDetail_orderInfo_container_itemtitle">配送方式：
                            </div>}
                            value={<span className="obligationsDetail_orderInfo_container_itemtValue">{orderDetail.express_name || '快递'}</span>}
                        />
                    </div>
                </div>
                {/* 价格信息 */}
                <div className="obligationsDetail_priceInfo">
                    <div className="obligationsDetail_priceInfo_container">
                        <Item
                            title={<div className="obligationsDetail_priceInfo_container_itemtitle">商品金额</div>}
                            value={<span className="obligationsDetail_priceInfo_container_itemtValue">¥ {payStatus.price}</span>}
                        />
                        <Item
                            title={<div className="obligationsDetail_priceInfo_container_itemtitle">恒豆可抵</div>}
                            value={<span className="obligationsDetail_priceInfo_container_itemtValue">{payStatus.price_q}</span>}
                        />
                        <Item
                            title={<div className="obligationsDetail_priceInfo_container_itemtitle">运费</div>}
                            value={<span className="obligationsDetail_priceInfo_container_itemtValue">¥ {orderDetail.freight}</span>}
                        />
                        <div className="obligationsDetail_priceInfo_allPrice">
                            <span>需付款：</span>
                            <span className="DINPro">￥{payStatus.price}+{payStatus.price_q}</span>
                            <span>恒豆</span>
                        </div>
                    </div>
                </div>
                {/* 支付Bar */}
                {
                    this.getFooterBar()
                }
            </div>
        )
    }

    public componentDidMount() {
        this.getData()
    }

    public componentWillMount() {
        this.countDown()
        this.timer = setInterval(this.countDown, 1000)
        clearInterval(this.timer)
    }

    private getFooterBar = () => {
        const { orderDetail } = this.props
        switch (orderDetail.status) {
            case 1: {
                return (
                    <div className="obligationsDetail_operationbar">
                        <Button className="obligationsDetail_operationbar_cancelBtn" onClick={this.handleOrderStatus.bind(this, '确定要取消订单么？', 7, '取消成功')}>取消订单</Button>
                        <Button className="obligationsDetail_operationbar_toPayBtn" onClick={() => { this.gotoUrl(`/selectPay?id=${orderDetail.order_pay_id}`) }}>去支付</Button>
                    </div>
                )
            }
            case 2: {
                return (
                    <div className="delivergoodsDetail_operationbar">
                        <div onClick={this.handleTuikuan}>申请退款</div>
                        <div>
                            <Button
                                className="delivergoodsDetail_operationbar_buyAgainBtn"
                                onClick={() => { this.gotoUrl(`/fillOrder?id=${orderDetail.id}&type=2`) }}
                            >
                                再次购买
                            </Button>
                            <Button className="delivergoodsDetail_operationbar_editBtn" onClick={this.handleResetOrder}>修改订单</Button>
                        </div>
                    </div>
                )
            }
            case 3: {
                return (
                    <div className="receivedDetail_operationbar">
                        {/* <div>申请退款</div> */}
                        <Button
                            className="receivedDetail_operationbar_buyAgainBtn"
                            onClick={() => { this.gotoUrl(`/fillOrder?id=${orderDetail.id}&type=2`) }}
                        >
                            再次购买
                        </Button>
                        <Button className="receivedDetail_operationbar_entryBtn" onClick={this.handleOrderStatus.bind(this, '确认收货么？', 4, '操作成功')}>确认收货</Button>
                    </div>
                )
            }
            case 4: {
                const { SET_USER_ORDER_INDEX, history } = this.props
                return (
                    <div className="orderCompleteDetail_operationbar">
                        <Button
                            className="orderCompleteDetail_operationbar_deleteBtn"
                            onClick={this.handleOrderStatus.bind(this, '确认要删除订单么？', 8, '删除成功', () => { SET_USER_ORDER_INDEX(0); history.goBack() })}
                        >
                            删除订单
                        </Button>
                        <div>
                            <Button className="orderCompleteDetail_operationbar_applyBtn" onClick={() => { this.gotoUrl(`/My/returnpolicy/${orderDetail.id}`) }}>申请售后</Button>
                            <Button
                                onClick={() => { this.gotoUrl(`/fillOrder?id=${orderDetail.id}&type=2`) }}
                                className="orderCompleteDetail_operationbar_buyAgainBtn"
                            >
                                再次购买
                            </Button>
                        </div>
                    </div>
                )
            }
            case 7: {
                const { SET_USER_ORDER_INDEX, history } = this.props
                return (
                    <div className="orderCancelDetail_operationbar">
                        <div onClick={this.handleOrderStatus.bind(this, '确认要删除订单么？', 8, '删除成功', () => { SET_USER_ORDER_INDEX(0); history.goBack() })}>删除订单</div>
                        <div>
                            <Button
                                className="orderCancelDetail_operationbar_buyAgainBtn"
                                onClick={() => { this.gotoUrl(`/fillOrder?id=${orderDetail.id}&type=2`) }}
                            >
                                再次购买
                            </Button>
                        </div>
                    </div>
                )
            }
            default: return ''
        }
    }

    private getPayStatus(status: string) {
        switch (status) {
            case 'weixin': return '微信'
            case 'alipay': return '支付宝'
            case 'balance': return '余额'
            default: return '在线支付'
        }
    }

    private getData() {
        const { userInfo, match, SET_USER_ORDERDETAIL } = this.props
        const id = match.params.id
        post('orderapi/orderDetail', {
            userId: userInfo.id,
            id
        }).then((data: any) => {
            SET_USER_ORDERDETAIL(data)
        })
    }

    private handleTuikuan = () => { 
        const { orderDetail, SET_USER_RETURN_DETAIL } = this.props
        SET_USER_RETURN_DETAIL(orderDetail)
        this.gotoUrl(`/My/returnpolicy/?type=1`) 
    }

    private getStatusNode(status: number, data: any) {
        const { timeText } = this.state
        const val = timeText.split(':')
        let time: any = moment(data.real_express_time * 1000).add(4, 'd').format('MM-DD')
        time = time.split('-')
        switch (status) {
            case 1: {
                return (
                    <div className="obligationsDetail_topInfo">
                        <div className="flex">
                            <div className="obligationsDetail_topInfo_leftIcon flex_1">
                                <Icon type="time" />
                                <span>等待付款</span>
                            </div>
                            <div>
                                <p>剩余：<span>{val[0]}小时{val[1]}分钟</span></p>
                                <p style={{whiteSpace: 'nowrap'}}>需付款：¥<span className="DINPro">{data.price}+{data.price_q}</span><span>恒豆</span></p>
                            </div>
                        </div>
                        <img src={require('../../../assets/order_detail_topbg.png')} />
                    </div>
                )
            }
            case 2: {
                return (
                    <div className="delivergoodsDetail_topInfo">
                        <div>
                            <div className="delivergoodsDetail_topInfo_leftIcon">
                                <Icon type="delivergoods" />
                                <span>待发货</span>
                            </div>
                        </div>
                        <img src={require('../../../assets/order_detail_topbg.png')} />
                    </div>
                )
            }
            case 3: {
                return (
                    <div className="receivedDetail_topInfo">
                        <div>
                            <div className="receivedDetail_topInfo_leftIcon">
                                <Icon type="delivergoods" />
                                <span>等待收货</span>
                            </div>
                            <div>
                                <p>{data.express_name}</p>
                                <p>预计{time[0]}月{time[1]}日 24:00前到达</p>
                            </div>
                        </div>
                        <img src={require('../../../assets/order_detail_topbg.png')} />
                    </div>
                )
            }
            case 4: {
                return (
                    <div className="orderCompleteDetail_topInfo">
                        <div>
                            <div className="orderCompleteDetail_topInfo_leftIcon">
                                <Icon type="complete" />
                                <span>已完成</span>
                            </div>
                        </div>
                        <img src={require('../../../assets/order_detail_topbg.png')} />
                    </div>
                )
            }
            case 7: {
                return (
                    <div className="orderCancelDetail_topInfo">
                        <div>
                            <div className="orderCancelDetail_topInfo_leftIcon">
                                <Icon type="error_circle" />
                                <span>已取消</span>
                            </div>
                        </div>
                        <img src={require('../../../assets/order_detail_topbg.png')} />
                    </div>
                )
            }
            default: return
        }
    }

    private countDown = () => {
        const { orderDetail } = this.props
        const nextTime: any = moment(orderDetail.create_time || '', 'YYYY-MM-DD HH:mm:ss').add(1, 'day')
        const time: any = moment()
        const val = moment.tz(nextTime - time, 'Africa/Abidjan').format('HH:mm')
        this.setState({
            timeText: val
        })
    }

    private handleOrderStatus = (message: string, status: number, msgInfo: string, callback?: () => void) => {
        const { userInfo, orderDetail, SET_USER_ORDERDETAIL } = this.props
        msg(message).then(() => {
            Toast.loading('', 0)
            post('orderapi/orderStatusHandle', {
                userId: userInfo.id,
                id: orderDetail.id,
                status
            }).then((data: any) => {
                const order = { ...orderDetail }
                order.status = status
                Toast.info(msgInfo, 2)
                setTimeout(() => { Toast.hide(); SET_USER_ORDERDETAIL(order); if (isFunc(callback)) { callback() } }, 2000)
            })
        })
    }

    private gotoUrl = (url: string) => {
        this.props.history.push(url)
    }

    private getStatusBtn = (status: number, data: any) => {
        switch (status) {
            case 2: {
                return (
                    <Button className="btn" onClick={this.handleAddCart.bind(this, data)}>加入购物车</Button>
                )
            }
            case 3: {
                return (
                    <Button className="btn" onClick={this.handleAddCart.bind(this, data)}>加入购物车</Button>
                )
            }
            case 4: {
                return (
                    <Button className="btn" onClick={() => { this.gotoUrl(`/My/returnpolicy/${data.id}`) }}>申请售后</Button>
                )
            }
            case 7: {
                return (
                    <Button className="btn" onClick={this.handleAddCart.bind(this, data)}>加入购物车</Button>
                )
            }
            default: return
        }
    }

    private handleResetOrder = () => {
        const { orderDetail } = this.props
        this.gotoUrl(`/My/barterDetail/${orderDetail.id}`)
    }

    private handleViewExpre = () => {
        const { history, SET_USER_EXPRESSINFO, orderDetail } = this.props
        SET_USER_EXPRESSINFO(orderDetail.expressInfo)
        history.push(`/My/orderLogistics/${orderDetail.id}`)
    }

    private handleAddCart = (data: any, e: any) => {
        e.preventDefault()
        const { userInfo } = this.props
        Toast.loading('', 0)
        post('cartapi/cartAdd', {
            userId: userInfo.id,
            listId: data.id,
            number: data.number
        }).then(() => {
            Toast.info('添加成功', 2)
        })
    }
}